import { createSource, deleteSource, getSource, updateSource } from "@/api";
import ImgUpload, { ImgUploadRef } from "@/components/dataEntry/ImgUpload";
import { useMount } from "@/hooks";
import { AppContext } from "@/providers";
import { PageData } from "@/util";
import { Button, Form, FormInstance, Input, message, Modal, Popconfirm, Table, TableColumnProps, TablePaginationConfig, Image } from "antd";
import { useCallback, useContext, useMemo, useRef, useState } from "react";
import { CategoryRecord } from "./CategoryType";

const Category = () => {
	const { REACT_APP_BASEURL } = useContext(AppContext);
	const columns = useMemo<TableColumnProps<CategoryRecord>[]>(
		() => [
			{ title: "分类名", dataIndex: "name" },
			{ title: "分类封面", dataIndex: "cover", render: (cover) => <Image src={`${REACT_APP_BASEURL}${cover}`} width={58} height={58} className="object-cover" /> },
			{
				render: (_, record) => (
					<>
						<Button
							type="primary"
							className="mr-2"
							onClick={() => {
								formRef.current?.setFieldsValue(record);
								imgUploadRef.current?.setUrl(`${REACT_APP_BASEURL}${record.cover}`);
								setOperateType("edit");
								setFormModalOpen(true);
							}}
						>
							编辑
						</Button>
						<Popconfirm
							onConfirm={async () => {
								await deleteSource({ id: record._id, source: "category" });
								await fetchCat();
								message.success("已删除");
							}}
							title="确认删除吗"
						>
							<Button danger>删除</Button>
						</Popconfirm>
					</>
				),
			},
		],
		[]
	);
	const [dataSource, setDataSource] = useState<CategoryRecord[]>([]);
	const [pageOptions, setPageOptions] = useState<TablePaginationConfig>({ pageSize: 10, current: 1, total: 0 });
	const fetchCat = useCallback(
		async (page = 1, pageSize = 10) => {
			const res = await getSource<PageData<CategoryRecord[]>>({
				source: "category",
				__fields__: "id,name,cover,createdTime,updatedTime",
				page,
				pageSize,
			});
			setDataSource(res.data?.data || []);
			setPageOptions({ ...pageOptions, total: Number(res.data?.total || 0) });
		},
		[pageOptions]
	);
	useMount(() => {
		fetchCat();
	});
	const [operateType, setOperateType] = useState<"add" | "edit">("add");
	const formRef = useRef<FormInstance>(null);
	const imgUploadRef = useRef<ImgUploadRef>(null);
	const [formModalOpen, setFormModalOpen] = useState(false);
	return (
		<>
			<Button
				className="mb-2"
				type="primary"
				onClick={() => {
					formRef.current?.resetFields();
					setOperateType("add");
					setFormModalOpen(true);
				}}
			>
				添加分类
			</Button>
			<Table
				columns={columns}
				dataSource={dataSource.map((item, key) => ({ ...item, key }))}
				pagination={{
					...pageOptions,
					onChange(current, pageSize) {
						setPageOptions({ pageSize, current });
						fetchCat(current, pageSize);
					},
				}}
			/>
			<Modal
				forceRender
				title={`${operateType === "add" ? "添加" : "编辑"}分类`}
				open={formModalOpen}
				onCancel={() => setFormModalOpen(false)}
				onOk={async () => {
					const { _id, name, cover } = (await formRef.current?.validateFields()) || {};
					if (operateType === "add") {
						await createSource({ source: "category", name, cover });
						await fetchCat();
						message.success("添加成功");
					}
					if (operateType === "edit") {
						await updateSource({ id: _id, source: "category", name, cover });
						await fetchCat();
						message.success("编辑成功");
					}
					setFormModalOpen(false);
				}}
			>
				<Form ref={formRef} labelCol={{ span: 4 }}>
					<Form.Item name="_id" hidden />
					<Form.Item label="分类名" name="name">
						<Input placeholder="请输入分类名" />
					</Form.Item>
					<Form.Item label="分类图片" name="cover">
						<ImgUpload ref={imgUploadRef} field="cover" formRef={formRef} />
					</Form.Item>
				</Form>
			</Modal>
		</>
	);
};

export default Category;
